package com.example.imserver.controller;

import com.example.imserver.entity.FileRecord;
import com.example.imserver.service.FileService;
import com.example.imserver.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
public class FileController {
    @Autowired
    private FileService fileService;
    
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return JwtUtil.getUserIdFromToken(token);
        }
        return null;
    }
    
    @PostMapping("/upload")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file,
                                          @RequestParam("fileType") String fileType,
                                          HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Long userId = getUserIdFromRequest(request);
        if (userId == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }
        
        try {
            FileRecord fileRecord = fileService.saveFile(file, fileType, userId);
            result.put("success", true);
            result.put("file", fileRecord);
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件上传失败: " + e.getMessage());
        }
        return result;
    }
}

